<template>
	<view class="create-order-container">
		<!-- 导航栏 -->
		<uni-nav-bar title="确认订单" left-icon="back" @clickLeft="goBack" />
		
		<!-- 商品信息 -->
		<view class="product-section">
			<view class="product-item">
				<image :src="product.imageUrl || '/static/default-product.png'" class="product-image" mode="aspectFill"></image>
				<view class="product-info">
					<text class="product-title">{{ product.title }}</text>
					<text class="product-desc">{{ product.description }}</text>
					<view class="price-row">
						<text class="current-price">¥{{ product.price }}</text>
						<text v-if="product.originPrice" class="origin-price">¥{{ product.originPrice }}</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 收货地址 -->
		<view class="address-section" v-if="orderForm.deliveryMethod === 2">
			<view class="section-title">收货地址</view>
			<view class="address-item" @click="selectAddress" v-if="selectedAddress">
				<view class="address-info">
					<view class="receiver-info">
						<text class="receiver-name">{{ selectedAddress.receiverName }}</text>
						<text class="receiver-phone">{{ selectedAddress.receiverPhone }}</text>
					</view>
					<text class="address-detail">{{ selectedAddress.province }}{{ selectedAddress.city }}{{ selectedAddress.district }}{{ selectedAddress.detailAddress }}</text>
				</view>
				<uni-icons type="right" size="16" color="#999"></uni-icons>
			</view>
			<view class="no-address" @click="selectAddress" v-else>
				<uni-icons type="location" size="20" color="#999"></uni-icons>
				<text class="no-address-text">请选择收货地址</text>
				<uni-icons type="right" size="16" color="#999"></uni-icons>
			</view>
		</view>
		
		<!-- 交易方式 -->
		<view class="delivery-section">
			<view class="section-title">交易方式</view>
			<view class="delivery-options">
				<view class="delivery-option" 
					  :class="{ active: orderForm.deliveryMethod === 1, disabled: !canSelectDeliveryMethod(1) }"
					  @click="selectDeliveryMethod(1)">
					<uni-icons type="location-filled" size="18" :color="orderForm.deliveryMethod === 1 ? '#007aff' : '#999'"></uni-icons>
					<text class="option-text">面交</text>
				</view>
				<view class="delivery-option" 
					  :class="{ active: orderForm.deliveryMethod === 2, disabled: !canSelectDeliveryMethod(2) }"
					  @click="selectDeliveryMethod(2)">
					<uni-icons type="email-filled" size="18" :color="orderForm.deliveryMethod === 2 ? '#007aff' : '#999'"></uni-icons>
					<text class="option-text">邮寄</text>
				</view>
			</view>
			<text class="delivery-tip" v-if="product.deliveryMethod">该商品支持：{{ getDeliveryMethodText(product.deliveryMethod) }}</text>
		</view>
		
		<!-- 价格协商 -->
		<view class="price-section">
			<view class="section-title">价格协商</view>
			<view class="price-input-row">
				<text class="price-label">出价：</text>
				<input class="price-input" 
					   type="digit" 
					   v-model="orderForm.finalPrice" 
					   placeholder="请输入出价"
					   :disabled="!canBargain" />
				<text class="price-unit">元</text>
			</view>
			<text class="price-tip" v-if="!canBargain">该商品不支持议价</text>
		</view>
		
		<!-- 买家留言 -->
		<view class="message-section">
			<view class="section-title">买家留言</view>
			<textarea class="message-input" 
					  v-model="orderForm.buyerMessage" 
					  placeholder="给卖家留言（选填）"
					  maxlength="200"></textarea>
		</view>
		
		<!-- 订单金额 -->
		<view class="amount-section">
			<view class="amount-row">
				<text class="amount-label">商品金额</text>
				<text class="amount-value">¥{{ orderForm.finalPrice || product.price }}</text>
			</view>
			<view class="amount-row">
				<text class="amount-label">数量</text>
				<text class="amount-value">{{ orderForm.quantity }}</text>
			</view>
			<view class="amount-row total">
				<text class="amount-label">总计</text>
				<text class="amount-value total-price">¥{{ totalAmount }}</text>
			</view>
		</view>
		
		<!-- 提交按钮 -->
		<view class="submit-section">
			<button class="submit-btn" 
					:disabled="!canSubmit" 
					:class="{ disabled: !canSubmit }"
					@click="submitOrder">
				提交订单
			</button>
		</view>
	</view>
</template>

<script>
import { createOrder } from '@/api/order.js'
import { getProductDetail } from '@/api/product.js'
import { getUserAddresses } from '@/api/address.js'
import { isLoggedIn, getToken, getUserInfo } from '@/utils/auth.js'

export default {
	data() {
		return {
			product: {},
			selectedAddress: null,
			orderForm: {
				productId: '',
				quantity: 1,
				finalPrice: '',
				deliveryMethod: 1, // 1=面交，2=邮寄
				buyerAddressId: null,
				buyerMessage: ''
			},
			loading: false
		}
	},
	computed: {
		// 是否可以议价
		canBargain() {
			return this.product.bargainOption === 2 || this.product.bargainOption === 3
		},
		// 订单总金额
		totalAmount() {
			const price = this.orderForm.finalPrice || this.product.price || 0
			return (price * this.orderForm.quantity).toFixed(2)
		},
		// 是否可以提交
		canSubmit() {
			if (!this.orderForm.finalPrice) return false
			if (this.orderForm.deliveryMethod === 2 && !this.selectedAddress) return false
			return true
		}
	},
	onLoad(options) {
		if (options.productId) {
			this.orderForm.productId = options.productId
			this.loadProductDetail()
		}
	},
	methods: {
		// 返回上一页
		goBack() {
			uni.navigateBack()
		},
		
		// 加载商品详情
		async loadProductDetail() {
			try {
				const res = await getProductDetail(this.orderForm.productId)
				if (res.success || res.code === 200) {
					this.product = res.data
					this.orderForm.finalPrice = this.product.price
					// 根据商品的交易方式设置默认值
					if (this.product.deliveryMethod) {
						this.orderForm.deliveryMethod = this.product.deliveryMethod
					}
				} else {
					uni.showToast({ title: res.message || '获取商品信息失败', icon: 'none' })
				}
			} catch (error) {
				console.error('加载商品详情失败:', error)
				uni.showToast({ title: '获取商品信息失败', icon: 'none' })
			}
		},
		
		// 选择交易方式
		selectDeliveryMethod(method) {
			if (!this.canSelectDeliveryMethod(method)) {
				return
			}
			this.orderForm.deliveryMethod = method
			if (method === 1) {
				// 面交时清除地址
				this.selectedAddress = null
				this.orderForm.buyerAddressId = null
			}
		},
		
		// 检查是否可以选择指定的交易方式
		canSelectDeliveryMethod(method) {
			if (!this.product.deliveryMethod) return true
			// 1=面交，2=邮寄，3=两者都可以
			if (this.product.deliveryMethod === 3) return true
			return this.product.deliveryMethod === method
		},
		
		// 获取交易方式文本
		getDeliveryMethodText(method) {
			const methodMap = {
				1: '面交',
				2: '邮寄', 
				3: '面交或邮寄'
			}
			return methodMap[method] || '未知'
		},
		
		// 选择收货地址
		selectAddress() {
			uni.navigateTo({
				url: '/pages/address/list?mode=select',
				events: {
					addressSelected: (address) => {
						this.selectedAddress = address
						this.orderForm.buyerAddressId = address.id
					}
				}
			})
		},
		
		// 提交订单
		async submitOrder() {
			if (this.loading) return
			
			// 检查登录状态
			if (!isLoggedIn()) {
				uni.showToast({ title: '请先登录', icon: 'none' })
				setTimeout(() => {
					uni.navigateTo({ url: '/pages/login/index' })
				}, 1500)
				return
			}
			
			// 打印调试信息
			console.log('当前登录状态:', isLoggedIn())
			console.log('当前Token:', getToken())
			console.log('当前用户信息:', getUserInfo())
			
			if (!this.canSubmit) {
				if (!this.orderForm.finalPrice) {
					uni.showToast({ title: '请输入出价', icon: 'none' })
					return
				}
				if (this.orderForm.deliveryMethod === 2 && !this.selectedAddress) {
					uni.showToast({ title: '请选择收货地址', icon: 'none' })
					return
				}
			}
			
			// 价格验证
			const finalPrice = parseFloat(this.orderForm.finalPrice)
			if (isNaN(finalPrice) || finalPrice <= 0) {
				uni.showToast({ title: '请输入有效的价格', icon: 'none' })
				return
			}
			
			// 议价验证
			if (!this.canBargain && finalPrice !== this.product.price) {
				uni.showToast({ title: '该商品不支持议价', icon: 'none' })
				return
			}
			
			this.loading = true
			
			try {
				const orderData = {
					productId: this.orderForm.productId,
					quantity: this.orderForm.quantity,
					finalPrice: finalPrice,
					deliveryMethod: this.orderForm.deliveryMethod,
					buyerAddressId: this.orderForm.buyerAddressId,
					buyerMessage: this.orderForm.buyerMessage
				}
				
				console.log('提交订单数据:', orderData)
			const res = await createOrder(orderData)
			console.log('订单创建响应:', res)
		
			if (res.success || res.code === 200) {
				uni.showToast({ title: '订单创建成功', icon: 'success' })
				
				// 跳转到订单详情或支付页面
				setTimeout(() => {
					const orderId = res.data.orderId || res.data.OrderId || res.data
					console.log('获取到的订单ID:', orderId)
					uni.redirectTo({
						url: `/pages/order/detail?id=${orderId}`
					})
				}, 1500)
			} else {
				console.error('订单创建失败:', res)
				const errorMsg = res.message || res.msg || '创建订单失败'
				uni.showToast({ title: errorMsg, icon: 'none' })
			}
			} catch (error) {
				console.error('提交订单异常:', error)
				let errorMsg = '创建订单失败'
				
				if (error.status === 401) {
					errorMsg = 'Token已过期，请重新登录'
					uni.showToast({ title: errorMsg, icon: 'none' })
					// 延迟跳转到登录页
					setTimeout(() => {
						uni.navigateTo({ url: '/pages/login/index' })
					}, 2000)
					return
				} else if (error.status === 403) {
					errorMsg = '权限不足'
				} else if (error.status >= 500) {
					errorMsg = '服务器错误，请稍后重试'
				} else if (error.message) {
					errorMsg = error.message
				}
				
				uni.showToast({ title: errorMsg, icon: 'none' })
			} finally {
				this.loading = false
			}
		}
	}
}
</script>

<style scoped>
.create-order-container {
	background-color: #f5f5f5;
	min-height: 100vh;
}

/* 商品信息 */
.product-section {
	background: white;
	margin-bottom: 10px;
	padding: 15px;
}

.product-item {
	display: flex;
	align-items: flex-start;
}

.product-image {
	width: 80px;
	height: 80px;
	border-radius: 8px;
	margin-right: 12px;
	flex-shrink: 0;
}

.product-info {
	flex: 1;
}

.product-title {
	font-size: 16px;
	font-weight: 500;
	color: #333;
	display: block;
	margin-bottom: 8px;
}

.product-desc {
	font-size: 14px;
	color: #666;
	display: block;
	margin-bottom: 8px;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.price-row {
	display: flex;
	align-items: center;
}

.current-price {
	font-size: 18px;
	font-weight: 600;
	color: #ff4757;
	margin-right: 8px;
}

.origin-price {
	font-size: 14px;
	color: #999;
	text-decoration: line-through;
}

/* 通用区块样式 */
.address-section,
.delivery-section,
.price-section,
.message-section,
.amount-section {
	background: white;
	margin-bottom: 10px;
	padding: 15px;
}

.section-title {
	font-size: 16px;
	font-weight: 500;
	color: #333;
	margin-bottom: 15px;
}

/* 收货地址 */
.address-item {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 12px 0;
}

.address-info {
	flex: 1;
}

.receiver-info {
	display: flex;
	align-items: center;
	margin-bottom: 8px;
}

.receiver-name {
	font-size: 16px;
	font-weight: 500;
	color: #333;
	margin-right: 12px;
}

.receiver-phone {
	font-size: 14px;
	color: #666;
}

.address-detail {
	font-size: 14px;
	color: #666;
	line-height: 1.4;
}

.no-address {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20px 0;
	color: #999;
}

.no-address-text {
	flex: 1;
	margin-left: 8px;
	font-size: 14px;
}

/* 交易方式 */
.delivery-options {
	display: flex;
	gap: 20px;
}

.delivery-option {
	display: flex;
	align-items: center;
	padding: 12px 20px;
	border: 1px solid #e0e0e0;
	border-radius: 8px;
	background: #f9f9f9;
	transition: all 0.3s;
}

.delivery-option.active {
	border-color: #007aff;
	background: #f0f8ff;
}

.delivery-option.disabled {
	opacity: 0.5;
	pointer-events: none;
}

.option-text {
	margin-left: 8px;
	font-size: 14px;
	color: #333;
}

.delivery-option.active .option-text {
	color: #007aff;
}

.delivery-tip {
	font-size: 12px;
	color: #666;
	margin-top: 8px;
}

/* 价格协商 */
.price-input-row {
	display: flex;
	align-items: center;
	margin-bottom: 8px;
}

.price-label {
	font-size: 14px;
	color: #333;
	margin-right: 12px;
}

.price-input {
	flex: 1;
	height: 40px;
	padding: 0 12px;
	border: 1px solid #e0e0e0;
	border-radius: 6px;
	font-size: 16px;
	margin-right: 8px;
}

.price-input:disabled {
	background: #f5f5f5;
	color: #999;
}

.price-unit {
	font-size: 14px;
	color: #666;
}

.price-tip {
	font-size: 12px;
	color: #999;
}

/* 买家留言 */
.message-input {
	width: 100%;
	height: 80px;
	padding: 12px;
	border: 1px solid #e0e0e0;
	border-radius: 6px;
	font-size: 14px;
	resize: none;
}

/* 订单金额 */
.amount-row {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 8px 0;
}

.amount-row.total {
	border-top: 1px solid #e0e0e0;
	margin-top: 8px;
	padding-top: 12px;
}

.amount-label {
	font-size: 14px;
	color: #666;
}

.amount-value {
	font-size: 14px;
	color: #333;
}

.total-price {
	font-size: 18px;
	font-weight: 600;
	color: #ff4757;
}

/* 提交按钮 */
.submit-section {
	padding: 20px 15px;
	background: white;
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	z-index: 100;
	border-top: 1px solid #e0e0e0;
}

.submit-btn {
	width: 100%;
	height: 48px;
	background: #007aff;
	color: white;
	border: none;
	border-radius: 24px;
	font-size: 16px;
	font-weight: 500;
}

.submit-btn.disabled {
	background: #ccc;
	color: #999;
}

/* 底部留白 */
.create-order-container {
	padding-bottom: 100px;
}
</style>